<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>商品秒杀抢购</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    body {
      font-family: 'Microsoft YaHei', sans-serif;
      background-color: #f5f5f5;
      color: #333;
      line-height: 1.6;
    }
    .container {
      max-width: 1200px;
      margin: 0 auto;
      padding: 20px;
    }
    .header {
      text-align: center;
      margin-bottom: 30px;
    }
    .header h1 {
      color: #e74c3c;
      font-size: 28px;
      margin-bottom: 10px;
    }
    .seckill-container {
      display: flex;
      justify-content: center;
      gap: 30px;
      flex-wrap: wrap;
    }
    .product-card {
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      width: 300px;
      padding: 20px;
      text-align: center;
      transition: transform 0.3s;
    }
    .product-card:hover {
      transform: translateY(-5px);
    }
    .product-image {
      width: 100%;
      height: 200px;
      object-fit: cover;
      border-radius: 5px;
      margin-bottom: 15px;
    }
    .product-title {
      font-size: 20px;
      margin-bottom: 10px;
      color: #333;
    }
    .product-price {
      display: flex;
      justify-content: center;
      align-items: baseline;
      margin-bottom: 15px;
    }
    .original-price {
      text-decoration: line-through;
      color: #999;
      font-size: 16px;
      margin-right: 10px;
    }
    .seckill-price {
      color: #e74c3c;
      font-size: 24px;
      font-weight: bold;
    }
    .countdown {
      background: #f8f8f8;
      padding: 10px;
      border-radius: 5px;
      margin-bottom: 15px;
      font-size: 16px;
    }
    .countdown span {
      color: #e74c3c;
      font-weight: bold;
    }
    .seckill-btn {
      background: #e74c3c;
      color: white;
      border: none;
      padding: 12px 25px;
      font-size: 16px;
      border-radius: 5px;
      cursor: pointer;
      width: 100%;
      transition: background 0.3s;
    }
    .seckill-btn:hover {
      background: #c0392b;
    }
    .seckill-btn.disabled {
      background: #95a5a6;
      cursor: not-allowed;
    }
    .result-message {
      margin-top: 15px;
      padding: 10px;
      border-radius: 5px;
      text-align: center;
    }
    .success {
      background: #d4edda;
      color: #155724;
    }
    .error {
      background: #f8d7da;
      color: #721c24;
    }
    .processing {
      background: #e2e3e5;
      color: #383d41;
    }
    .stock-info {
      margin-top: 10px;
      font-size: 14px;
      color: #666;
    }
    .login-message {
      text-align: center;
      margin-top: 20px;
      color: #e74c3c;
    }
  </style>
</head>
<body>
<div class="container">
  <div class="header">
    <h1>限时抢购</h1>
  </div>

  <div class="seckill-container">
    <div class="product-card">
      <div class="product-price">
        <span class="seckill-price">¥1000</span>
      </div>
      <div class="countdown">
        距离结束: <span id="countdown">00:00:00</span>
      </div>
      <div class="stock-info">
        剩余库存: <span id="stock">100</span>件
      </div>
      <button id="seckillBtn" class="seckill-btn">立即抢购</button>
      <div id="resultMessage" class="result-message" style="display: none;"></div>
    </div>
  </div>

  <div class="login-message" id="loginMessage" style="display: none;">
    请先登录后再参与抢购
  </div>
</div>

<script>
  // 模拟用户ID，实际项目中应从登录信息获取
  const userId = localStorage.getItem('userId') || Math.floor(Math.random() * 1000000);
  localStorage.setItem('userId', userId);

  // 活动ID
  const activityId = 1;

  // 倒计时结束时间（示例：1小时后结束）
  const endTime = new Date();
  endTime.setHours(endTime.getHours() + 1);

  // 更新倒计时
  function updateCountdown() {
    const now = new Date();
    const diff = endTime - now;

    if (diff <= 0) {
      document.getElementById('countdown').textContent = '活动已结束';
      document.getElementById('seckillBtn').classList.add('disabled');
      document.getElementById('seckillBtn').disabled = true;
      return;
    }

    const hours = Math.floor(diff / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((diff % (1000 * 60)) / 1000);

    document.getElementById('countdown').textContent =
            `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  }

  // 初始化倒计时
  updateCountdown();
  setInterval(updateCountdown, 1000);

  // 获取库存信息
  function fetchStock() {
    fetch('/seckill/stock?activity_id=' + activityId)
            .then(response => response.json())
            .then(data => {
              if (data.code === 1) {
                document.getElementById('stock').textContent = data.data.stock;

                if (data.data.stock <= 0) {
                  document.getElementById('seckillBtn').classList.add('disabled');
                  document.getElementById('seckillBtn').disabled = true;
                  document.getElementById('seckillBtn').textContent = '已售罄';
                }
              }
            })
            .catch(error => console.error('获取库存失败:', error));
  }

  // 初始化库存
  fetchStock();
  setInterval(fetchStock, 5000); // 每5秒刷新一次库存

  // 抢购按钮点击事件
  document.getElementById('seckillBtn').addEventListener('click', function() {
    if (this.disabled) return;

    this.disabled = true;
    this.textContent = '抢购中...';

    const resultMessage = document.getElementById('resultMessage');
    resultMessage.style.display = 'none';

    // 发起抢购请求
    fetch('/seckill', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        activity_id: activityId,
        user_id: userId
      })
    })
            .then(response => response.json())
            .then(data => {
              if (data.code === 1) {
                // 抢购请求已接收，开始轮询结果
                pollSeckillResult();
              } else {
                showMessage(data.msg, 'error');
                this.disabled = false;
                this.textContent = '立即抢购';
              }
            })
            .catch(error => {
              console.error('抢购请求失败:', error);
              showMessage('网络错误，请重试', 'error');
              this.disabled = false;
              this.textContent = '立即抢购';
            });
  });

  // 轮询抢购结果
  function pollSeckillResult() {
    const maxAttempts = 20; // 最大尝试次数
    let attempts = 0;

    const checkResult = () => {
      attempts++;

      fetch('/seckill/result?activity_id=' + activityId + '&user_id=' + userId)
              .then(response => response.json())
              .then(data => {
                if (data.code === 1) {
                  // 抢购成功
                  showMessage('抢购成功！订单号: ' + data.data.order_no, 'success');
                  document.getElementById('seckillBtn').textContent = '已抢购';
                  document.getElementById('seckillBtn').classList.add('disabled');
                  fetchStock(); // 刷新库存
                } else if (data.code === 0) {
                  // 抢购失败
                  showMessage(data.msg, 'error');
                  document.getElementById('seckillBtn').disabled = false;
                  document.getElementById('seckillBtn').textContent = '立即抢购';
                } else if (data.code === 2 && attempts < maxAttempts) {
                  // 仍在处理中，继续轮询
                  showMessage('抢购处理中，请稍候...', 'processing');
                  setTimeout(checkResult, 1000);
                } else {
                  // 超时或未知状态
                  showMessage('抢购处理超时，请查看订单', 'error');
                  document.getElementById('seckillBtn').disabled = false;
                  document.getElementById('seckillBtn').textContent = '立即抢购';
                }
              })
              .catch(error => {
                console.error('查询结果失败:', error);
                if (attempts < maxAttempts) {
                  setTimeout(checkResult, 1000);
                } else {
                  showMessage('查询结果失败，请稍后查看订单', 'error');
                  document.getElementById('seckillBtn').disabled = false;
                  document.getElementById('seckillBtn').textContent = '立即抢购';
                }
              });
    };

    checkResult();
  }

  // 显示消息
  function showMessage(message, type) {
    const resultMessage = document.getElementById('resultMessage');
    resultMessage.textContent = message;
    resultMessage.className = 'result-message ' + type;
    resultMessage.style.display = 'block';
  }

  // 模拟检查用户是否登录
  if (!userId) {
    document.getElementById('loginMessage').style.display = 'block';
    document.getElementById('seckillBtn').disabled = true;
    document.getElementById('seckillBtn').classList.add('disabled');
  }
</script>
</body>
</html>